<?php
/**
 * INITTAB
 *
 * @version 0.2a 
 */

// No direct access
defined( "__DEENZO__" ) or die( "deenzo$" ); 

// Loading dependencies
coreutil( "cmdl" ) or kill( "cmdl$" );
sbin( "sql" )      or kill( "sql$" );
 
function inittab( $argv ) {

    $argv    = (object) cmdl( $argv );
    
    /* Looking for INIT scripts */
    $inittab = sql( "inittab.( uid      eq '$argv->uid' 
                             & runlevel eq $argv->runlevel 
                             & kind     eq '$argv->kind' ).!ORDER( p ASC )", "-lo" );
    
    // No registered INIT script, return true
    if ( !is_array( $inittab ) ) return true;
 
    foreach ( $inittab as $init ) {
    
        $sh = $init->sh;  
        
        /* Support for Absolute and Canonical Paths */
        if ( preg_match( "/^(?!\.|\/|[A-Z]\:)/", $init->sh ) )
            $sh = __DIR__ . "/$init->sh";

        /* Check if SH exists, if not erase it and send Kill-all signal */
        if ( !sh( $sh, "-of" ) ) { 
            
            sql( "inittab.( pid eq $init->pid )", null );
            
            kill( $sh );
            
        }
        
        /* Execute function */
        if ( $func = $init->func )
            eval( "$init->func();" );
    
    } 

}

function initscript( $argv, $args = "" ) {

    // Receive and process COMMAND-line
	$argv = (object) cmdl( $argv );
	
	/* Check for UID and attach current RUNLEVEL */
	if ( defined( "__UID__" ) )
		$argv->uid  = __UID__;
	
	$argv->runlevel = __RUNLEVEL__;
	
	/* Register script for event trigger */
	return ( is_bool( sql( "inittab", (array) $argv ) ) );

}